/**
 * The init function 
 */
$(function() {
	// stuffs to do when the devisce is ready
	document.addEventListener('deviceready', onDeviceReady, false);
	// add a event listener on the back button
	document.addEventListener("backbutton", backKeyDown, true);

	// set the onclick events on the logo image
	$('.logo-image').click(function(event){
		alert('pippo');
		goToHome();
	});
	
  	// if the find quests button is clicked try to find quests in the current city and go to the 
  	// accept quest page
  	$('#findQuests').click(function(){
    
		// show the loading widget
		showLoading('Please wait. CityQuest is trying to locate your current city ...');
		
		// get the current position
  		navigator.geolocation.getCurrentPosition(onCurrentPositionSuccess,onCurrentPositionError,{
  			enableHighAccuracy: true
  		});
  	})
  	
  	// when the user clicks on start quest button creates the map
	$('#start-quest-button').click(function(){
		alert('byh');
	  	// get the page height
		var pageHeight = $('#quest-main').css('height');
		// get the footer height
		var footerHeight = $('#index-footer').css('height');
		// get the header height
		var headerHeight = $('#index-header').css('height');
		// set the map height to full screen
		$('#map-canvas-start-quest').css('height', function(){
			return parseInt(pageHeight) - ((parseInt(headerHeight) * 2)  + parseInt(footerHeight));
		});
		mapBo.init("Gioco");
		// creates the map with the game areas 
  		/*navigator.geolocation.getCurrentPosition(gameAreasOnCurrentPositionSuccess,gameAreasOnCurrentPositionError,{
  			enableHighAccuracy: true
  		});*/
	});
});

/**  
 * this is used to do some stuffs when the device is ready. Like disable back button 
 * and so on. 
*/
function onDeviceReady(){
	// overrides the listener of the back button
	navigator.app.overrideBackbutton(true);	

}

/*
 * Do nothing when the back button is pressed 
 */
function backKeyDown(){
	return false; 
}

/**
 * This is used when the current position was successfully retrieved  
*/
function gameAreasOnCurrentPositionSuccess(aPosition){
	// the current latitude
	var currentPositionLatitude = aPosition.coords.latitude
	// the current longitude
	var currentPositionLongitude = aPosition.coords.longitude
	
	// create the google map
	var startLatLng = new google.maps.LatLng(currentPositionLatitude, currentPositionLongitude);
  	$('#map-canvas-start-quest').gmap({'center': startLatLng, 'bounds': false, 'zoom': 14});
  	$('#map-canvas-start-quest').gmap('addMarker', {'position': startLatLng, 'bounds': false});
	$('#map-canvas-start-quest').gmap('addShape', 'Circle', { 
				'strokeWeight': 0, 
				'fillColor': "#008595", 
				'fillOpacity': 0.25, 
				'center': startLatLng, 
				'radius': 5,
				'clickable': false 
	});
  	
  	// hide the loading widget
  	hideLoading();

    // show the current city
    var currentAddress = getCurrentAddress(startLatLng); 

}

/**
 * This is used when the current position was not successfully retrieved  
*/
function gameAreasOnCurrentPositionError(anError){
	// print the error
	alert('code: '    + anError.code    + '\n' +
          'message: ' + anError.message + '\n');
    
    // hide the loading widget
  	hideLoading();
}

/**
 * This is used when the current position was successfully retrieved  
*/
function onCurrentPositionSuccess(aPosition){
	// the current latitude
	var currentPositionLatitude = aPosition.coords.latitude
	// the current longitude
	var currentPositionLongitude = aPosition.coords.longitude
	
	// create the google map
	var startLatLng = new google.maps.LatLng(currentPositionLatitude, currentPositionLongitude);
  	$('#map_canvas').gmap({'center': startLatLng, 'bounds': false, 'zoom': 15});
  	$('#map_canvas').gmap('addMarker', {'position': startLatLng, 'bounds': false});
	$('#map_canvas').gmap('addShape', 'Circle', { 
				'strokeWeight': 0, 
				'fillColor': "#008595", 
				'fillOpacity': 0.25, 
				'center': startLatLng, 
				'radius': 5,
				'clickable': false 
	});
  	
  	// hide the loading widget
  	hideLoading();

    // show the current city
    var currentAddress = getCurrentAddress(startLatLng); 

}

/**
 * This is used when the current position was not successfully retrieved  
*/
function onCurrentPositionError(anError){
	// print the error
	alert('code: '    + anError.code    + '\n' +
          'message: ' + anError.message + '\n');
    
    // hide the loading widget
  	hideLoading();
}

/**
 * Get the current city address
 */
function getCurrentAddress(aPosition){
  	// show the current city
  	var geocoder = new google.maps.Geocoder();
  	if (geocoder) {
    	geocoder.geocode({ 'latLng': aPosition}, function (results, status) {
       	if (status == google.maps.GeocoderStatus.OK) {
       		// update the popup
			$('#startQuestDialogTitle').html('You are currently in ' + results[0].formatted_address + '. There is a quest in this zone. Do you want to start the quest?');
			// opn the popup
			$('#startQuestDialog').popup("open");
		}
       	else {
        	$('#address').html('Geocoding failed: '+status);
        		return "Geocoding failed: " + status;
       		}
    	}); 
    }
}

/** 
 * Shows the loading widget
*/
function showLoading(aMessage){
	$.mobile.loading( 'show', {
		text: aMessage,
		textVisible: true,
		textonly: false
	});	
}

/**
 * Hides to loading widget
*/
function hideLoading(){
	$.mobile.loading( 'hide')
}

/**
 * Goes to the home page
*/
function goToHome(){
	location.hash = '';
}


